package game;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.lwjgl.*;
import org.lwjgl.opengl.*;

import game.Game;
import game.net.Server;

public class Game {

	private boolean run = true;
	private int width = 800, height = 600;
	private String title = "Game V0.0.1";
	private int fps = 80;
	private float fov = 45.0f;
	private String name;
	private Server server;
	private boolean onlineMode = false;

	private void start() throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		if (onlineMode) {
			System.out.println("Enter name: ");
			name = br.readLine();
			System.out.println("Enter ip: ");
			String ip = br.readLine();
			System.out.println("Enter port: ");
			int port = Integer.parseInt(br.readLine());
			System.out.println("Connecting to server at ip " + ip + ", port " + port);

			server = new Server(name, ip, port);
			server.connect();
		}
		
		try {
			Display.setDisplayMode(new DisplayMode(width, height));
			Display.setTitle(title);
			Display.create();
		} catch (LWJGLException e) {
			e.printStackTrace();
		}

		init();

		long time = (Sys.getTime() * 1000) / Sys.getTimerResolution();
		long lastTime = time;
		int delta;

		while (run) {
			time = (Sys.getTime() * 1000) / Sys.getTimerResolution();
			delta = (int) (time - lastTime);
			lastTime = time;

			if (Display.isCloseRequested()) {
				break;
			}

			update(delta);
			render();

			Display.sync(fps);
			Display.update();

		}
		Display.destroy();
	}

	private void init() {
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(fov, width / height, 0.1f, 10000.1f);
		glMatrixMode(GL_MODELVIEW);
		glEnable(GL_DEPTH_TEST);

		System.out.println("OpenGL version: " + GL11.glGetString(GL11.GL_VERSION));
	}

	private void update(int delta) {
		//server.send(Server.POS_ID + "," + name + "," + x + "," + y);
	}

	private void render() {

	}

	public static void main(String[] args) {
		System.setProperty("org.lwjgl.librarypath", new File("lib/native").getAbsolutePath());
		Game game = new Game();
		try {
			game.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
